package org.kingtop.mybatis.kengen;

import java.sql.Statement;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.keygen.KeyGenerator;
import org.apache.ibatis.mapping.MappedStatement;
import org.kingtop.cache.IRedisTemplate;
import org.kingtop.mybatis.util.KeyGeneratorUtil;

/**
 * Redis自增key，只适合Long类型的主键
 * @author 陈金波
 * @date   2018年1月10日 下午9:45:15    
 * @Copyright: 2018 chen jinbo. All rights reserved.
 */
public class RedisKeyGenerator implements KeyGenerator {
	
	/**
	 * REDIS默认自增key的名称
	 */
	public static final String REDIS_INCREAMENT_NAME = "KEY_GENERATOR_REDIS_ID";

	public static RedisKeyGenerator INSTANCE = null;

	/**
	 * redis类
	 */
	private final IRedisTemplate redisTemplate;

	/**
	 * redis自增字段的名称
	 */
	private final String redisIncrementName;

	public RedisKeyGenerator(IRedisTemplate redisTemplate, String redisIncrementName) {
		super();
		this.redisTemplate = redisTemplate;
		this.redisIncrementName = redisIncrementName;
	}

	@Override
	public void processBefore(Executor executor, MappedStatement ms, Statement stmt, Object parameter) {
		if (redisTemplate == null) {
			throw new NullPointerException(getClass().getName() + " redisTemplate is null");
		}
		Long value = redisTemplate.incr(redisIncrementName);
		KeyGeneratorUtil.processBatch(executor, ms, stmt, KeyGeneratorUtil.getParameters(parameter), value);
	}

	@Override
	public void processAfter(Executor executor, MappedStatement ms, Statement stmt, Object parameter) {
	}

	/**
	 * @return the redisTemplate
	 */
	public IRedisTemplate getRedisTemplate() {
		return redisTemplate;
	}

}
